package com.weharvest.edu.utlis;

import com.fasterxml.jackson.annotation.JsonInclude;

import org.codehaus.jackson.map.DeserializationConfig.Feature;
import org.codehaus.jackson.map.ObjectMapper;

import java.io.IOException;
import java.text.SimpleDateFormat;

public class JsonUtil {

    private static ObjectMapper objectMapper;
    static {
        objectMapper = generateMapper();
    }

    public static <T> T fromJson(String json, Class<T> clazz) throws IOException {
        return clazz.equals(String.class) ? (T) json : objectMapper.readValue(json, clazz);
    }


    private static ObjectMapper generateMapper( ) {
        ObjectMapper customMapper = new ObjectMapper();
        // 设置输出时包含属性的风格
//        customMapper.set
        // 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
        customMapper.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 禁止使用int代表Enum的order()來反序列化Enum,非常危險
//        customMapper.configure(Feature.FAIL_ON_NUMBERS_FOR_ENUMS, true);
        // 所有日期格式都统一为以下样式
//        customMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        return customMapper;
    }
}
